<!-- 训练 -->

<template>
  <div class="training-page">
    <div class="header">
      <h1>模型训练</h1>
      <p class="subtitle">配置训练参数，启动深度学习模型训练任务</p>
    </div>
    
    <div class="training-content">
      <div class="config-section">
        <div class="card">
          <h2>训练配置</h2>
          <form @submit.prevent="handleStartTraining" class="training-form">
            <div class="form-group">
              <label>选择模型架构:</label>
              <select v-model="config.modelName" class="form-select">
                <option value="YOLOv8">YOLOv8 (目标检测)</option>
                <option value="SegFormer">SegFormer (语义分割)</option>
                <option value="ResNet">ResNet (图像分类)</option>
                <option value="EfficientNet">EfficientNet (图像分类)</option>
      </select>
            </div>
            
            <div class="form-group">
              <label>训练轮次 (Epochs):</label>
              <input type="number" v-model.number="config.epochs" min="1" max="1000" class="form-input" />
            </div>
            
            <div class="form-group">
              <label>批次大小 (Batch Size):</label>
              <input type="number" v-model.number="config.batchSize" min="1" max="128" class="form-input" />
            </div>
            
            <div class="form-group">
              <label>学习率:</label>
              <input type="number" v-model.number="config.learningRate" step="0.0001" min="0.0001" max="1" class="form-input" />
            </div>
            
            <div class="form-group">
              <label>数据集路径:</label>
              <div class="dataset-input">
                <input v-model="config.datasetPath" placeholder="选择数据集文件夹" class="form-input" readonly />
                <button type="button" @click="selectDataset" class="select-btn">选择</button>
              </div>
            </div>
            
            <div class="form-group">
              <label>输出目录:</label>
              <div class="dataset-input">
                <input v-model="config.outputPath" placeholder="选择输出目录" class="form-input" readonly />
                <button type="button" @click="selectOutputDir" class="select-btn">选择</button>
              </div>
            </div>
            
            <div class="form-actions">
              <button type="submit" :disabled="trainingStore.isTraining" class="start-btn primary-btn">
                <span v-if="trainingStore.isTraining">🔄 训练中...</span>
                <span v-else>🚀 开始训练</span>
              </button>
              <button type="button" @click="stopTraining" :disabled="!trainingStore.isTraining" class="stop-btn danger-btn">
                停止训练
              </button>
            </div>
    </form>
        </div>
      </div>
      
      <div class="status-section">
        <div class="card">
          <h2>训练状态</h2>
          <div v-if="trainingStore.trainingStatus" class="training-status">
            <div class="status-item">
              <span class="status-label">状态:</span>
              <span class="status-value" :class="statusClass">{{ trainingStore.trainingStatus }}</span>
            </div>
            <div class="status-item" v-if="trainingStore.trainingProgress">
              <span class="status-label">进度:</span>
              <div class="progress-bar">
                <div class="progress-fill" :style="{ width: trainingStore.trainingProgress + '%' }"></div>
              </div>
              <span class="progress-text">{{ trainingStore.trainingProgress }}%</span>
            </div>
            <div class="status-item" v-if="trainingStore.currentEpoch">
              <span class="status-label">当前轮次:</span>
              <span class="status-value">{{ trainingStore.currentEpoch }}/{{ config.epochs }}</span>
            </div>
            <div class="status-item" v-if="trainingStore.trainingLoss">
              <span class="status-label">损失值:</span>
              <span class="status-value">{{ trainingStore.trainingLoss.toFixed(4) }}</span>
            </div>
          </div>
          <div v-else class="no-status">
            <p>暂无训练任务</p>
          </div>
        </div>
        
        <div class="card">
          <h2>训练历史</h2>
          <div v-if="trainingStore.trainingHistory.length > 0" class="history-list">
            <div v-for="(record, index) in trainingStore.trainingHistory" :key="record.id" class="history-item">
              <div class="history-info">
                <div class="history-model">{{ record.modelName }}</div>
                <div class="history-time">{{ formatTime(record.startTime) }}</div>
              </div>
              <div class="history-status" :class="record.status">
                {{ record.status === 'completed' ? '完成' : record.status === 'running' ? '运行中' : record.status === 'stopped' ? '已停止' : '失败' }}
              </div>
            </div>
          </div>
          <div v-else class="no-history">
            <p>暂无训练历史</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useTrainingStore } from '../store/training'

const trainingStore = useTrainingStore()

// 训练配置
const config = ref({
  modelName: 'YOLOv8',
  epochs: 100,
  batchSize: 32,
  learningRate: 0.001,
  datasetPath: '',
  outputPath: ''
})

// 计算状态样式类
const statusClass = computed(() => {
  const status = trainingStore.trainingStatus
  if (status.includes('完成')) return 'status-completed'
  if (status.includes('失败')) return 'status-failed'
  if (status.includes('训练中')) return 'status-running'
  return 'status-idle'
})

// 开始训练
async function handleStartTraining() {
  if (!config.value.datasetPath) {
    alert('请选择数据集路径')
    return
  }
  
  if (!config.value.outputPath) {
    alert('请选择输出目录')
    return
  }
  console.log('[renderer] 启动训练，配置:', config.value)
  await trainingStore.startTraining(config.value)
}

// 停止训练
function stopTraining() {
  if (confirm('确定要停止当前训练任务吗？')) {
    console.log('[renderer] 停止训练')
    trainingStore.stopTraining()
  }
}

// 选择数据集路径
async function selectDataset() {
  console.log('[renderer] 选择数据集路径')
  const result = await window.electronAPI.selectDirectory('选择数据集文件夹')
  console.log('[renderer] selectDirectory 返回:', result)
  if (result) {
    config.value.datasetPath = result
  }
}

// 选择输出目录
async function selectOutputDir() {
  console.log('[renderer] 选择输出目录')
  const result = await window.electronAPI.selectDirectory('选择输出目录')
  console.log('[renderer] selectDirectory 返回:', result)
  if (result) {
    config.value.outputPath = result
    }
}

// 格式化时间
function formatTime(isoString) {
  const date = new Date(isoString)
  return date.toLocaleString('zh-CN')
}
</script>

<style scoped>
.training-page {
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 32px;
}

.header h1 {
  color: #001529;
  margin-bottom: 8px;
}

.subtitle {
  color: #666;
  font-size: 16px;
}

.training-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.config-section, .status-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.training-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-select, .form-input {
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  background-color: white;
}

.form-select:focus, .form-input:focus {
  outline: none;
  border-color: #1677ff;
  box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.2);
}

.dataset-input {
  display: flex;
  gap: 8px;
}

.dataset-input .form-input {
  flex: 1;
}

.select-btn {
  padding: 10px 16px;
  background-color: #666;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.form-actions {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

.start-btn, .stop-btn {
  flex: 1;
  padding: 12px 24px;
  font-size: 16px;
  font-weight: 500;
}

.training-status {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
}

.status-value {
  font-weight: 500;
}

.status-value.status-completed {
  color: #52c41a;
}

.status-value.status-failed {
  color: #ff4d4f;
}

.status-value.status-running {
  color: #1677ff;
}

.status-value.status-idle {
  color: #999;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #1677ff;
  transition: width 0.3s ease;
}

.progress-text {
  min-width: 50px;
  text-align: right;
  font-weight: 500;
  color: #1677ff;
}

.no-status, .no-history {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 8px;
}

.history-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.history-model {
  font-weight: 500;
  color: #333;
}

.history-time {
  font-size: 12px;
  color: #666;
}

.history-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.history-status.completed {
  background-color: #f6ffed;
  color: #52c41a;
}

.history-status.running {
  background-color: #e6f7ff;
  color: #1677ff;
}

.history-status.failed {
  background-color: #fff2f0;
  color: #ff4d4f;
}
</style>